package hash.hashcode;

import java.util.HashSet;

/**
 * 
 * @Title: HashCodeTest.java 
 * @Package hash.hashcode 
 * @Description: 测试jdk的hashCode()方法
 * @author CandyWall   
 * @date 2021年1月12日 下午5:32:02 
 * @version V1.0
 */
public class HashCodeTest {
    public static void main(String[] args) {
        int a = 42;
        System.out.println(((Integer)a).hashCode());
        int b = -42;
        System.out.println(((Integer)b).hashCode());
        double c = 3.141592653589793;
        System.out.println(((Double)c).hashCode());
        double pi = Math.PI;
        System.out.println(pi);
        System.out.println(((Double)pi).hashCode());
        String str = "I love java!";
        System.out.println(str.hashCode());
        System.out.println("I love java!".hashCode());
        System.out.println("================");
        Student stu = new Student("2021211123", "张三", 25);
        System.out.println(stu.hashCode());
        System.out.println(stu);
        System.out.println(new Student("2021211123", "张三", 25));
        System.out.println(new Student("2021211123", "李四", 25));
        System.out.println(new Student("2021211123", "zhangsan", 25));
        System.out.println(new Student("2021211123", "ZHANGSAN", 25));
        System.out.println("================");
        HashSet<Student> set = new HashSet<>();
        for(int i = 0; i < 5; i++) {
            set.add(new Student("2021211123", "张三", 25));
        }
        for(Student student : set) {
            System.out.println(student);
        }
        System.out.println(new Student("2021211123", "张三", 25).equals(new Student("2021211123", "张三", 25)));
        System.out.println(new Student("2021211123", "zhangsan", 25).equals(new Student("2021211123", "ZHANGSAN", 25)));
        
    }
}

class Student {
    private String stuNo;
    private String stuName;
    private int age;
    public Student(String stuNo, String stuName, int i) {
        super();
        this.stuNo = stuNo;
        this.stuName = stuName;
        this.age = i;
    }

    @Override
    public int hashCode() {
        int B = 31;
        int hash = 0;
        hash = hash * B + age;
        hash = hash * B + stuName.toUpperCase().hashCode();
        hash = hash * B + stuNo.toUpperCase().hashCode();
        return hash;
    }
    
    @Override
    public boolean equals(Object obj) {
        if(this == obj) {
            return true;
        }
        if(obj == null) {
            return false;
        }
        if(this.getClass() != obj.getClass()) {
            return false;
        }
        Student stu = (Student) obj;
        return this.stuNo.equals(stu.stuNo) && 
               this.stuName.toLowerCase().equals(stu.stuName.toLowerCase()) && 
               this.age == stu.age;
    }
}
